package com.example.project;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import com.example.project.dao.SQLiteComer;
import com.example.project.dao.SQLiteValoracion;
import com.example.project.model.Comer;
import com.example.service.ComerParcelable;
import com.example.service.ValoracionsParcelable;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;


public class DateBaseService extends Service {
	
	public static final int MSG_REGISTER_RESTAURANT=0;
	public static final int MSG_REGISTER_RECOMENDATION=1;
	public static final int MSG_UPDATE_LOCATION=2;
	public static final int MSG_GET_RESTAURANT=3;
	public static final int MSG_GET_RECOMENDATION=4;
	public static final int MSG_GET_ALL_RESTAURANTS=5;
	public static final int MSG_DELETE_RESTAURANT=7;
	public static final int MSG_GET_ALL_VALORACIONES=8;
	
	static final String KEY_RESTAURANT = "restaurant"; 
 	static final String KEY_ID = "id";
 	static final String KEY_NAME = "nom";
 	static final String KEY_DIRECTION = "direccio";
 	static final String KEY_TELEFON = "telefon";
 	static final String KEY_THUMB_URL = "thumb_url";
 	static final String KEY_IMG="img";
 	static final String KEY_LATITUD="latitud";
 	static final String KEY_LONGITUD="longitud";
 	static final String KEY_DIST="distancia";
 	
 	static final String KEY_VALORACIO = "tupla"; 
	static final String KEY_IDRESTAURANT = "idComer"; 
 	static final String KEY_IDVALORACION = "idValoracion";
 	static final String KEY_NOTA="nota";
 	static final String KEY_COMENTARIO="comentario";
 	static SQLiteComer comerDB;
	//RestaurantParcelable inRestaurant;
	
	public DateBaseService() {
		
	}

	class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) 
        {
        	 	
        	Bundle b;
       	 	comerDB =
                    new SQLiteComer(DateBaseService.this, "comer", null, 1);
       	 	SQLiteDatabase db  = comerDB.getWritableDatabase();
       	 	
       	    SQLiteValoracion valoracionDB =
                 new SQLiteValoracion(DateBaseService.this, "valoracion", null, 1);
    	 	SQLiteDatabase valoraciondb  = valoracionDB.getWritableDatabase();
       	 	
       	 	ComerParcelable inComer;
       	    ValoracionsParcelable inVal;
       	 	
            switch (msg.what) 
            {
            
       
            
                case MSG_REGISTER_RESTAURANT:
                	b=msg.getData();
                	b.setClassLoader(ComerParcelable.class.getClassLoader());
                	inComer= (ComerParcelable) b.getParcelable("RestaurantParcelable");
                	ContentValues values = new ContentValues();
                	
                	
                	values.put(KEY_IMG,inComer.getRestaurant().getFoto());
                	values.put(KEY_DIRECTION,inComer.getRestaurant().getDireccion());
                	Geocoder g= new Geocoder(getBaseContext(), Locale.getDefault());
                	List<Address> add = new ArrayList<Address>(); 
                	try {
    					add=g.getFromLocationName(inComer.getRestaurant().getDireccion(), 1);
    					values.put(KEY_LATITUD, String.valueOf(add.get(0).getLatitude()));
                    	values.put(KEY_LONGITUD, String.valueOf(add.get(0).getLongitude()));
    				} catch (IOException e1) {
    					// TODO Auto-generated catch block
    					e1.printStackTrace();
    				}
                	
                	values.put(KEY_NAME, inComer.getRestaurant().getNombre());
                	values.put(KEY_TELEFON, inComer.getRestaurant().getTelefono());
                	
                	//values.put(KEY_LATITUD, "0");
                	//values.put(KEY_LONGITUD, "0");
                	
                	//insert de la resta de taules
					db.insert("comer",null, values);
                    break;
                    
                case MSG_REGISTER_RECOMENDATION: 
                	b=msg.getData();
                	b.setClassLoader(ValoracionsParcelable.class.getClassLoader());
                	inVal= (ValoracionsParcelable) b.getParcelable("ValoracionParcelable");
                	ContentValues values2 = new ContentValues();
                	
                	
                	values2.put(KEY_IDRESTAURANT,inVal.getValoracion().getIdRestaurante());
                	values2.put(KEY_COMENTARIO,inVal.getValoracion().getComentario());
                	values2.put(KEY_NOTA, inVal.getValoracion().getNota());
                	
					valoraciondb.insert("valoracion",null, values2);
                	break;
                case MSG_UPDATE_LOCATION:
                	
                	//
                    break;
                case MSG_GET_RESTAURANT:
                	b = msg.getData();
                	b.setClassLoader(ComerParcelable.class.getClassLoader());
                	inComer= (ComerParcelable) b.getParcelable("RestaurantParcelable");
                	Cursor c = db.rawQuery("SELECT  * FROM  comer" + "WHERE "+KEY_ID+"="+inComer.getId()+";", null);
                	Comer r=new Comer();
                	r.setIdComer(Integer.parseInt(c.getString(0)));
                	r.setFoto(c.getString(1));
                	r.setDireccion(c.getString(2));
                	//r.setLatitude(c.getString(3));
                	//r.setLongitude(c.getString(4));
                	r.setNombre(getString(5));
                	r.setTelefono(c.getString(6));
                	
                	ComerParcelable cp = new ComerParcelable(0, "user", r);
                	Bundle b2 = new Bundle();
        			b2.putParcelable("RestaurantParcelable",cp);
        			Message msg2 = Message.obtain(null, DateBaseService.MSG_GET_RESTAURANT, 0, 0);
        			msg2.setData(b2);
        				try {
        					msg.replyTo.send(msg2);
        				} catch (RemoteException e) {
        					e.printStackTrace();
        				}
                	
        				catch (Exception e) {
        					e.printStackTrace();                     
        				}

         			break;
         			
                case MSG_GET_RECOMENDATION:
                	//mirar com voleu treballar amb els recomanacions
                	break;
                	
                case MSG_GET_ALL_VALORACIONES:
                	  ArrayList<HashMap<String, String>> valoracionsList = new ArrayList<HashMap<String, String>>();
                  	  Cursor c2 = valoraciondb.rawQuery("SELECT  * FROM  valoracion;", null);
                	
	                	if (c2.moveToFirst()) {
	                	     do {
	                	    	HashMap<String, String> map = new HashMap<String, String>();

	                	    	map.put(KEY_IDVALORACION, c2.getString(0));
	                	    	map.put(KEY_IDRESTAURANT, c2.getString(1));
	                	    	map.put(KEY_NOTA, c2.getString(2));
	                	    	map.put(KEY_COMENTARIO,c2.getString(3));
	                	    	
	
	                   			valoracionsList.add(map);
	                	     } while(c2.moveToNext());
	                	}
	                	
	                	ValoracionsParcelable cp3 = new ValoracionsParcelable(0, "user",valoracionsList);
	                	Bundle b3 = new Bundle();
	        			b3.putParcelable("ValoracionParcelable",cp3);
	        			Message msg3 = Message.obtain(null, Menjar.MSG_OBTAIN_ALL_VALORACIONS, 0, 0);
	        			msg3.setData(b3);
	        				try {
	        					msg.replyTo.send(msg3);
	        				} catch (RemoteException e) {
	        					e.printStackTrace();
	        				}
	                	
	        				catch (Exception e) {
	        					e.printStackTrace();                     
	        				}
            				
                	break;
                	
                case MSG_DELETE_RESTAURANT:
                	b = msg.getData();
                	b.setClassLoader(ComerParcelable.class.getClassLoader());
                	inComer= (ComerParcelable) b.getParcelable("RestaurantParcelable");
                	db.delete("comer", KEY_ID + "=" + inComer.getId(), null);
                	break;
                	
                case MSG_GET_ALL_RESTAURANTS:
              	  ArrayList<HashMap<String, String>> restaurantsList = new ArrayList<HashMap<String, String>>();
              	  Cursor c1 = db.rawQuery("SELECT  * FROM  comer;", null);
              	
	                	if (c1.moveToFirst()) {
	                	     do {
	                	    	HashMap<String, String> map = new HashMap<String, String>();

	                	    	map.put(KEY_ID, c1.getString(0));
	                	    	map.put(KEY_THUMB_URL, c1.getString(1));
	                	    	map.put(KEY_DIRECTION, c1.getString(2));
	                	    	map.put(KEY_LATITUD,c1.getString(3));
	                	    	map.put(KEY_LONGITUD, c1.getString(4));
	                	    	map.put(KEY_NAME,c1.getString(5));
	                	    	map.put(KEY_TELEFON, c1.getString(6));
	
	                   			restaurantsList.add(map);
	                	     } while(c1.moveToNext());
	                	}
	                	
	                	ComerParcelable cp4 = new ComerParcelable(0, "user", restaurantsList);
	                	Bundle b4 = new Bundle();
	        			b4.putParcelable("RestaurantParcelable",cp4);
	        			Message msg4 = Message.obtain(null, Delete_Restaurant_DB.MSG_OBTAIN_ALL_RESTAURANTS, 0, 0);
	        			msg4.setData(b4);
	        				try {
	        					msg.replyTo.send(msg4);
	        				} catch (RemoteException e) {
	        					e.printStackTrace();
	        				}
	                	
	        				catch (Exception e) {
	        					e.printStackTrace();                     
	        				}
          				
              	break;
              
              	
               default:
                    super.handleMessage(msg);
            }
        }
    }

   final  Messenger mMessenger = new Messenger(new IncomingHandler());
	@Override
	public IBinder onBind(Intent intent) {
		 
		return mMessenger.getBinder();
		    
	}
	
}
